import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 华为一键登录按钮
class HWLoginButton extends StatefulWidget {
  final Function(String) onSuccessMessage;
  final Function(String) onFaildMessage;
  const HWLoginButton(
      {Key? key, required this.onSuccessMessage, required this.onFaildMessage})
      : super(key: key);

  @override
  State<HWLoginButton> createState() => _HWLoginButtonState();
}

class _HWLoginButtonState extends State<HWLoginButton> {
  late MethodChannel _channel;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return _getPlatformFaceView();
  }

  Widget _getPlatformFaceView() {
    return OhosView(
      viewType: 'com.rex.custom.ohos/loginButtonView',
      onPlatformViewCreated: _onPlatformViewCreated,
      creationParams: const <String, dynamic>{'initParams': 'hello world'},
      creationParamsCodec: const StandardMessageCodec(),
    );
  }

  void _onPlatformViewCreated(int id) {
    _channel = MethodChannel('com.rex.custom.ohos/loginButtonView$id');
    final controller = HWLoginController._(
      _channel,
    );
    controller.customDataStream.listen((data) {
      if (data.startsWith('error-')) {
        String msg = data.replaceAll('error-', '');
        widget.onFaildMessage(msg);
      } else {
        widget.onSuccessMessage(data);
      }
    });
  }
}

class HWLoginController {
  final MethodChannel _channel;
  final StreamController<String> _controller = StreamController<String>();

  HWLoginController._(
    this._channel,
  ) {
    _channel.setMethodCallHandler(
      (call) async {
        switch (call.method) {
          case 'getMessageFromOhosView':
            // 从native端获取数据
            final result = call.arguments as String;
            _controller.sink.add(result);
            break;
        }
      },
    );
  }

  Stream<String> get customDataStream => _controller.stream;

  // 发送数据给native
  Future<void> sendMessageToOhosView(String message) async {
    await _channel.invokeMethod(
      'getMessageFromFlutterView',
      message,
    );
  }
}
